
function onStateChange()
{

    var state = wave.getState();
    var notebook_id = state.get("notebook_id");
    var revision = state.get("revision");
    if (notebook_id) {
        notebook_load($("#nerdview"), notebook_id, true);
    }
    else {
        var new_id = "Wave: " + wave.getHost().getId() + " @ " + Date();
        state.submitDelta({'notebook_id': new_id});
    }
}

function onGetNotebook(http_response)
{
    var state = wave.getState();
    var notebook_id = state.get("notebook_id");
    var v = $("<p>in <b>" + notebook_id + "</b></p>")
    v.addClass('notebook_details');
    $("#nerdview").html(v);
    $("#nerdview").append(http_response.text);
    gadgets.window.adjustHeight();
}

function OpenPalette(){
   	d = $("#dialog").dialog();
   	d.addClass("small");
   	d.removeClass("invisible");
   	a = $("#accordion").accordion();  
   	a.addClass("small");
   	a.removeClass("invisible");
 	var params = {};
 	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
 	var userid = wave.getViewer().getId();
 	gadgets.io.makeRequest("__url__/gadget?notebook=" + userid + ":FavoriteFormulas&rnd=" + Math.random(),
 		 function(x) { $("#formulas").html(x.text); }, params);
	gadgets.io.makeRequest("__url__/gadget?notebook=" + userid + ":FavoriteConst&rnd=" + Math.random(),
 		 function(x) { $("#constants").html(x.text); }, params);
}

function up()
{
    var state = wave.getState();
    var revision = state.get('revision', 0);
    state.submitDelta({'revision': revision+1});
}

function whenAddPosted(data, status)
{
    up();
}

function onAdd()
{
    var state = wave.getState();
    var notebook = state.get("notebook_id");
    $.get("__url__/sign", {'content': $("#formula_edit").val(),
                           'notebook': notebook,
                           'noredir': 1}, whenAddPosted, "script")
}

function preparePanel()
{
    var add_entry = $("<input type='entry' id='formula_edit'></input>");
    var add_button = $("<img src='__url__/px/gui/24x24/Plus.gif' />")
    add_button.click(onAdd)
    
    add_entry.addClass('orb');
    add_button.addClass('orb');
    
    $("#panel").html(add_entry);
    $("#panel").append(add_button);

    var pal_button = $("<img src='__url__/px/gui/24x24/Applications.gif' />");
    pal_button.click(OpenPalette);
    pal_button.addClass('orb');

    $("#panel").append(pal_button);
}

function init()
{
	if (wave && wave.isInWaveContainer()) {
		wave.setStateCallback(onStateChange);
	}
    //preparePanel();
	$('#accordion').accordion();
	$('#palette').dialog({autoOpen: false, height: 400});
}
